<?php

namespace App\Console\Commands\Article;

use App\Models\Article;
use App\Services\Http;
use App\Services\LogTrait;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Console\Command;

class Wx extends Command
{
    use LogTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'article:wx {page=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws \Exception
     * @return mixed
     */
    public function handle()
    {
        $this->logName = 'article:wx';
        try{
            $appId = 68865;
            $appSecret = '2d5dd0dd23b7460c8dbf172b5dffc694';
            $page  = $this->argument('page');
            $params = [
                'showapi_appid' => $appId,
                'page' => $page,
                'url'  => 'MzAxNTEzNDUxNA=='
            ];

            $params = $this->buildParams($params, $appSecret);
            $url = 'http://route.showapi.com/1797-1?' . $params;
            $http = Http::getInstance();
            try {
                $response = $http->get($url);
            }catch (RequestException $exception){
                $this->logWrite('get article fail! error->'.$exception->getResponse()->getBody()->getContents().'');
                return false;
            }
            $json = $response->getBody()->getContents();
            $result = json_decode($json, true);
            $this->dataToDb($result['showapi_res_body']['article_info'] ?? []);

        }catch (\Exception $exception){
            $this->logWrite($exception->getMessage());
            $this->logWrite($exception->getTraceAsString());
        }
    }

    /**
     * @author Haohuang
     * @email  huanghao1054@gmail.com
     * @since   2019/9/9
     * @param $data
     * @throws \Exception
     */
    protected function dataToDb($data)
    {
        $http = Http::getInstance();
        foreach ( $data as $row ) {
            $this->logWrite(json_encode($row, JSON_UNESCAPED_UNICODE));
            preg_match('/读报 |/', $row['title'], $match);
            $sort = !empty($match[0]) ? 1 : 99;

            $response = $http->get($row['url']);
            $contents = $response->getBody()->getContents();
            preg_match('/var t="\d+",n="(\d+)",s=".*?";/', $contents, $match);
            $publishTime = date('Y-m-d H:i:s', $match[1]);

            $item = [
                'title'         => $row['title'],
                'abstract'      => $row['abstract'],
                'cover_img'     => $row['cover_img'],
                'mp_name'       => $row['mp_name'],
                'sort'          => $sort,
                'publish_time'  => $publishTime,
                'url'           => $row['url']
            ];
            Article::query()->updateOrCreate([
                'url' => $row['url']
            ], $item);
        }
    }

    protected function buildParams($params, $appSecret)
    {
        $paraStr = "";
        $signStr = "";
        ksort($params);
        foreach ($params as $key => $val) {
            if ($key != '' && $val != '') {
                $signStr .= $key.$val;
                $paraStr .= $key.'='.urlencode($val).'&';
            }
        }
        $signStr .= $appSecret;//排好序的参数加上secret,进行md5
        $sign = strtolower(md5($signStr));
        $paraStr .= 'showapi_sign='.$sign;//将md5后的值作为参数,便于服务器的效验
        return $paraStr;
    }
}
